<template>
  <div class="department-management">
    <div class="header">
      <h2>科室管理</h2>
      <el-button type="primary" @click="handleAdd" v-if="hasPermission">
        <el-icon><Plus /></el-icon>
        添加科室
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="form-inline">
        <el-form-item label="科室名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入科室名称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="科室编码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入科室编码"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable filterable>
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd" v-if="hasPermission">新增科室</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 科室列表 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%; margin-top: 20px;">
      <el-table-column prop="name" label="科室名称" min-width="180" />
      <el-table-column prop="code" label="科室编码" min-width="120" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="location" label="位置" min-width="120" />
      <el-table-column prop="phone" label="联系电话" min-width="120" />
      <el-table-column prop="level" label="层级" width="80">
        <template #default="{ row }">
          {{ row.level === 1 ? '一级科室' : '二级科室' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" v-if="hasPermission">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)" >编辑</el-button>
          <el-button type="success" link @click="handleAddSub(row)" v-if="row.level === 1">添加子科室</el-button>
          <el-button type="danger" link @click="handleDelete(row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getDepartmentTree } from '@/api/business'
import { deleteDepartment } from '@/api/admin'
import { useUserStore } from '@/stores/user'
import { addDialog } from '@/components/gDialog'
import DepartmentHandle from './adminModal/departmentHandle.vue'

const userStore = useUserStore()
const hasPermission = computed(() => userStore.isAdmin)

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 一级科室列表（用于选择上级科室）
const parentDepartments = ref([])

// 页面加载时获取数据
onMounted(() => {
  fetchDepartments()
})

// 获取科室列表
const fetchDepartments = async () => {
  loading.value = true
  try {
    const response = await getDepartmentTree(searchForm)
    if (response.code === 200) {
      tableData.value = response.data
      // 更新一级科室列表
      parentDepartments.value = response.data.filter(dept => dept.level === 1)
    } else {
      ElMessage.error(response.message || '获取科室列表失败')
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('获取科室列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchDepartments()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    status: ''
  })
  fetchDepartments()
}

// 新增科室
const handleAdd = () => {
  addDialog({
    title: '新增科室',
    width: '500px',
    component: DepartmentHandle,
    props: {
      level: 1,
      parentDepartments: parentDepartments.value
    },
    callBack: (success) => {
      if (success) {
        fetchDepartments()
      }
    }
  })
}

// 新增子科室
const handleAddSub = (row) => {
  addDialog({
    title: '新增子科室',
    width: '500px',
    component: DepartmentHandle,
    props: {
      parentId: row.id,
      level: 2,
      parentDepartments: parentDepartments.value,
      initialData: {
        parentCode: row.code
      }
    },
    callBack: (success) => {
      if (success) {
        fetchDepartments()
      }
    }
  })
}

// 编辑科室
const handleEdit = (row) => {
  addDialog({
    title: '编辑科室',
    width: '500px',
    component: DepartmentHandle,
    props: {
      id: row.id,
      level: row.level,
      parentId: row.parentId,
      parentDepartments: parentDepartments.value,
      initialData: row
    },
    callBack: (success) => {
      if (success) {
        fetchDepartments()
      }
    }
  })
}

// 删除科室
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该科室吗？删除后不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteDepartment(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchDepartments()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除科室失败:', error)
      ElMessage.error('删除失败')
    }
  })
}
</script>

<style scoped>
.department-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}
</style>
